<?php
namespace app\admin\controller;

use app\admin\model\CityArea;
use think\Request;
use app\admin\model\ShippingTemplate as TemplateModel;
use app\admin\model\ShippingRule as RuleModel;
use app\common\BaseController;
use think\facade\Db;

class ShippingTemplate extends BaseController
{
    // 运费模板列表
    public function index()
    {
        $list = TemplateModel::with('rules')->append(['type_text'])->order('id desc')->select();
        return $this->success('ok', $list);
    }
    
    // 创建运费模板
    public function create(Request $request)
    {
        $data = $request->post();
        $validate = new \app\common\validate\ShippingTemplate();
        if (!$validate->scene('create')->check($data)) {
            return $this->error('参数验证失败', $validate->getError());
        }
        
        Db::startTrans();
        try {
            $template = TemplateModel::create([
                'name' => $data['name'],
                'type' => $data['type'],
                'is_free_shipping' => $data['is_free_shipping'] ?? 0,
                'valuation_rules' => json_encode($data['rules']),
                'create_time' => time(),
                'update_time' => time()
            ]);
            
            if (!empty($data['rules'])) {
                foreach ($data['rules'] as $rule) {
                    RuleModel::create([
                        'template_id' => $template->id,
                        'region_ids' => $rule['region_ids'],
                        'region_names' => $rule['region_names'],
                        'first_unit' => $rule['first_unit'],
                        'first_price' => $rule['first_price'],
                        'continue_unit' => $rule['continue_unit'],
                        'continue_price' => $rule['continue_price'],
                        'create_time' => time()
                    ]);
                }
            }
            
            Db::commit();
            return $this->success('创建成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->success('创建失败:'.$e->getMessage());
        }
    }
    

       /**
     * 更新运费模板状态
     * @param Request $request
     * @param int $id 模板ID
     * @return \think\response\Json
     */
    public function updateTemplateStatus(Request $request, $id)
    {
        $data = $request->post();
        // 检查模板是否存在
        $template = TemplateModel::find($id);
        if (!$template) {
            return $this->error('模板不存在');
        }
        Db::startTrans();
        try {
            // 更新模板基本信息
            $template->status = $data['status'];
            $template->update_time = time();
            $template->save();
            Db::commit();
            return $this->success('更新成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('更新失败: '.$e->getMessage());
        }
    }

   /**
     * 更新运费模板
     * @param Request $request
     * @param int $id 模板ID
     * @return \think\response\Json
     */
    public function update(Request $request, $id)
    {
        $data = $request->post();
        
        // 验证数据
        $validate = new \app\common\validate\ShippingTemplate();
        if (!$validate->scene('update')->check($data)) {
            return $this->error('参数验证失败', $validate->getError());
        }
        
        // 检查模板是否存在
        $template = TemplateModel::find($id);
        if (!$template) {
            return $this->error('模板不存在');
        }
        
        Db::startTrans();
        try {
            // 更新模板基本信息
            $template->save([
                'name' => $data['name'],
                'type' => $data['type'],
                'is_free_shipping' => $data['is_free_shipping'] ?? 0,
                'valuation_rules' => json_encode($data['rules']),
                'update_time' => time()
            ]);
            
            // 先删除旧规则
            RuleModel::where('template_id', $id)->delete();
            
            // 添加新规则
            if (!empty($data['rules'])) {
                foreach ($data['rules'] as $rule) {
                    RuleModel::create([
                        'template_id' => $template->id,
                        'region_ids' => $rule['region_ids'],
                        'region_names' => $rule['region_names'],
                        'first_unit' => $rule['first_unit'],
                        'first_price' => $rule['first_price'],
                        'continue_unit' => $rule['continue_unit'],
                        'continue_price' => $rule['continue_price'],
                        'create_time' => time(),
                        'update_time' => time()
                    ]);
                }
            }
            
            Db::commit();
            return $this->success('更新成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('更新失败: '.$e->getMessage());
        }
    }
    
    // 删除运费模板
    public function delete($id)
    {
        $template = TemplateModel::find($id);
        if (!$template) {
            return $this->error('模板不存在');
        }
        Db::startTrans();
        try {
            $template->delete();
            RuleModel::where('template_id', $id)->delete();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('删除失败: '.$e->getMessage());
        }
       
        return $this->success('删除成功');
    }
    
    // 获取地区数据
    public function regions(Request $request)
    {
        $parent_id = $request->param('parent_id', 0);
        $list = CityArea::where('parent_id',$parent_id)->field('id,type,name')->select();
        return $this->success('ok',$list);
    }
}